package pers.bc.utils.yonyou;

import java.awt.Image; 
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.ui.pub.filesystem.FileManageServletClient;
import nc.vo.pub.BusinessException;
import nc.vo.rm.active.RMActiveConst;

/**
 * @author limeic 活动图片工具类
 * 
 */
public class RMPhotoUtils {

	private IFileSystemService fileService;

	public IFileSystemService getFileService() {
		if (fileService == null) {
			fileService = NCLocator.getInstance().lookup(
					IFileSystemService.class);
		}
		return fileService;
	}

	/**
	 * 图片的byte[]做压缩处理
	 * 
	 * @param photo
	 * @return
	 * @throws Exception
	 */
	public  byte[] processPhoto(byte[] photo) throws Exception {
		//创建临时文件路径
		FileSystemView fsv = FileSystemView.getFileSystemView();
		String defaultDirectory = fsv.getDefaultDirectory().getPath() + "\\"
				+ RMActiveConst.ACTFILERES;// 获取系统用户的文档目录+rmactivephoto文件夹
		File fileSavePath = new File(defaultDirectory);
		if (!fileSavePath.exists()) {
			fileSavePath.mkdirs();// 创建本地文件保存和下载路径
		}
		// 5M以上
		if (photo.length > 5242880) {
			photo = photoCompress(photo, 10,defaultDirectory);
		}
		// 2M以上
		if (photo.length > 2045728) {
			photo = photoCompress(photo, 8,defaultDirectory);
		}
		// 1M以上
		if (photo.length > 1022864) {
			photo = photoCompress(photo, 6,defaultDirectory);
		}
		// 500K以上
		if (photo.length > 511432) {
			photo = photoCompress(photo, 4,defaultDirectory);
		}
		// 250K以上
		if (photo.length > 255716) {
			photo = photoCompress(photo, 2,defaultDirectory);
		}
		// 80K以上
		if (photo.length > 81920) {
			photo = photoCompress(photo, 2,defaultDirectory);
		}
		// 上传完毕，清除文件
		File fileRoot = new File(defaultDirectory);
		clearLocalFile(fileRoot);
		return photo;
	}

	/**
	 * 具体压缩图片算法
	 * 
	 * @param photo
	 * @return
	 */
	private  byte[] photoCompress(byte[] srcPhoto, int value,String defaultDirectory)
			throws Exception {
		// 源图片
		Image src = new ImageIcon(srcPhoto).getImage();
		int w = src.getWidth(null);
		int h = src.getHeight(null);
		if ((w > h && w <= 120) || (w < h && h <= 120)) {
			return srcPhoto;
		}
		int nw = w / value;
		int nh = h / value;
		BufferedImage targetImage = new BufferedImage(nw, nh,
				BufferedImage.TYPE_INT_RGB);
		targetImage.getGraphics().drawImage(src, 0, 0, nw, nh, null);
		String fileName = defaultDirectory+"\\"+System.currentTimeMillis() + ".jpg";
		File outImage = new File(fileName);
		// 生成压缩图
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(outImage);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
			encoder.encode(targetImage);
		} finally {
			IOUtils.closeQuietly(fos);
		}
		// 将压缩图转化为byte[]
		FileInputStream fis = null;
		byte[] imgData = null;
		try {
			imgData = new byte[(int) outImage.length()];
			fis = new FileInputStream(outImage);
			fis.read(imgData);
		} finally {
			IOUtils.closeQuietly(fis);
		}
		// 删除生成的文件
		if (outImage.exists()) {
			outImage.delete();
		}
		return imgData;
	}

	/**
	 * 将Byte[]转化为File
	 * 
	 * @param bytes
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static File createFileFromBytes(byte[] bytes, String fileName)
			throws BusinessException{
		File file = null;
		FileOutputStream fos = null;
		try {
			if (!StringUtils.isEmpty(fileName)) {
				file = new File(fileName);
			}
			fos = new FileOutputStream(file);
			fos.write(bytes);
		} catch (IOException e) {
			Logger.error(e.getMessage());
			throw new BusinessException(e.getMessage());
		} finally{
			IOUtils.closeQuietly(fos);
		}
		return file;
	}

	/**
	 * 上传图片（客户端发起，从客户端本地上传到服务器）
	 * 
	 * 
	 * FileManageServletClient
	 * 
	 * @author xujinf
	 * @param file
	 * @param dsName
	 * @param pk_active
	 * @param fullServerPath
	 * @param creator
	 */
	public void uploadFile(File file, String dsName, String pk_active,
			String fullServerPath, String creator) throws Exception {
		FileInputStream fis = null;
		try {
			if (file != null) {
				fis = new FileInputStream(file);
			}
			if (!StringUtils.isEmpty(dsName) && !StringUtils.isEmpty(pk_active)
					&& !StringUtils.isEmpty(fullServerPath)
					&& !StringUtils.isEmpty(creator)) {
				// 修改时，如果服务器端已有，则删除
				String deleteFileFullServerPath = pk_active + "/" + fullServerPath;
				if (getFileService().isExist(deleteFileFullServerPath)) {
					getFileService().deleteNCFileNode(deleteFileFullServerPath);
				}
				// 开始上传
				FileManageServletClient.uploadFile(dsName, pk_active,
						fullServerPath, fis, creator, file.length());
			}
		} catch (IOException e) {
			Logger.error(e.getMessage());
			throw new BusinessException(e.getMessage());
		} finally{
			IOUtils.closeQuietly(fis);
		}
		
	}

	/**
	 * 下载图片（客户端发起，从服务器下载到客户端本地）
	 * 
	 * FileManageServletClient
	 * 
	 * @author xujinf
	 * @param pk_active
	 * @param activecode
	 * @param photoType
	 *            (0, 下载原图; 1, 下载压缩图)
	 * @throws Exception
	 */
	public void downlodFile(String pk_active, int photoType) throws Exception {
		String dsName = WorkbenchEnvironment.getInstance().getLoginBusiCenter()
				.getDataSourceName();// 数据库设计名称
		String photoTypeName = null;
		switch (photoType) {
		case 0:
			photoTypeName = RMActiveConst.PHOTONAME;
			break;
		case 1:
			photoTypeName = RMActiveConst.MCPHOTONAME;
			break;
		default:
			photoTypeName = RMActiveConst.MCPHOTONAME;
			break;
		}
		String fullServerPath = pk_active + "\\" + photoTypeName + pk_active
				+ ".jpg";// 图片在服务器的全路径
		// 判断文件是否存在
		if (!getFileService().isExist(fullServerPath)) {
			return;
		}
		FileSystemView fsv = FileSystemView.getFileSystemView();
		String defaultDirectory = fsv.getDefaultDirectory().getPath() + "\\";
		String fileres = defaultDirectory + RMActiveConst.ACTFILERES;
		// 图片保存到本地文件夹中
		File photoFolder = new File(fileres);
		if (!photoFolder.exists()) {
			photoFolder.mkdirs();
		}
		// 图片路径为mcphoto_+活动主键.jpg
		String localPhotoPath = fileres + "\\" + photoTypeName + pk_active
				+ ".jpg";
		File localPhoto = new File(localPhotoPath);
		if (localPhoto.exists()) {
			// 删除本地文件
			localPhoto.delete();
		}
		OutputStream out = null;
		try {
			localPhoto.createNewFile();
			try {
				out = new FileOutputStream(localPhoto);
				FileManageServletClient.downloadFile(dsName, fullServerPath,
						out);
			} finally {
				if (out != null) {
					out.close();
				}
			}
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
	}

	/**
	 * 在客户端，获取本地图片，并转换为byte[]
	 * 
	 * @author xujinf
	 * @param pk_active
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 */
	public byte[] getLocalFile(String pk_active) throws BusinessException,
			IOException {
		FileSystemView fsv = FileSystemView.getFileSystemView();
		String defaultDirectory = fsv.getDefaultDirectory().getPath();
		// 本地图片文件夹
		String fileres = defaultDirectory + "\\" + RMActiveConst.ACTFILERES;
		// 压缩图片路径为mcphoto_+活动编码.jpg
		String localPhotoPath = fileres + "\\" + RMActiveConst.MCPHOTONAME
				+ pk_active + ".jpg";
		File photo = new File(localPhotoPath);
		// 若文件不存在，返回null
		if (!photo.exists()) {
			return null;
		}
		// 将图片转化为byte[]
		FileInputStream fis = null;
		byte[] bytes = null;
		try {
			bytes = new byte[(int) photo.length()];
			fis = new FileInputStream(photo);
			fis.read(bytes);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		} finally {
			fis.close();// 关闭流
		}
		// 获取完毕，清除文件
		File fileRoot = new File(fileres);
		clearLocalFile(fileRoot);
		return bytes;
	}

	/**
	 * 清除fileRoot文件夹（包括自己）下全部文件
	 * 
	 * @author xujinf
	 * @param fileRoot
	 */
	public void clearLocalFile(File fileRoot) throws BusinessException {
		if (!fileRoot.exists()) {
			return;
		} else {
			File[] files = fileRoot.listFiles();// 全部子文件（夹）
			if (files != null) {
				for (File file : files) {
					clearLocalFile(file);// 递归
					file.delete();
				}
			}
			fileRoot.delete();
		}
	}
}
